CSCA Toast Manager. Ремейк
Автор: Casper Gaming (+ правки от Phileas`а)
Версия: 1.1.2 (14.07.2020)
Тип: Модификация Window_Base
Оригинал
Важный факт: я ленив и разработка на мейкере для меня имеет далеко не самый высокий приоритет (это просто хобби), это стоит учесть в моей истории.
В ходе разработки своего проекта решил привинтить к нему скрипт, позволяющий показывать всплывающие сообщения (тосты). Как-то быстро на глаза попался скрипт от Pheonix KageDesu. На первый взгляд он казался красивеньким и прикольным. Оказалось, что скрипт иногда глючит, тосты могут подолгу не исчезать с экрана, иногда появляются с опозданием. Я написал на соседнем форуме в авторской теме скрипта, однако KageDesu, хоть и заходит регулярно на Светлую, ничего мне не ответил(
Далее у меня было 3 варианта:
0) Написать свой скрипт.
1) Исправить скрипт KageDesu.
2) Найти другой скрипт.
Учитывая важный факт из начала моей истории, читатель легко поймёт, что я стремился потратить минимум усилий. Вариант 0 был для меня крайней мерой. Какое-то время я поковырялся в 1 варианте, однако из-за авторского подхода мне пришлось бы переделать почти весь скрипт. Фон тоста в этом скрипте отрисовывается, по сути, как однотонная картинка (что объясняет кривую работу этой штуки), а это довольно негибко, да и некрасиво (просто текст на чёрном полупрозрачном прямоугольнике).
Беглый поиск в интернете дал мне неплохой скрипт от Casper Gaming. Однако текст отрисовывался в нём примитивно (в нём не работали мейкерские теги: \c, \i...), а окно тоста появлялось примерно там же, где диалоговое окно снизу. Переместить окно в левый угол и поменять его размер, естественно, оказалось очень легко, а вот над парсингом текста пришлось повозиться.
Что в итоге:
- скрипт показывает по команде тост в левом верхнем углу экрана;
- теперь работать с тостом можно наподобие мейкерского сообщения (с тегами, иконками и прочим);
- по умолчанию тост имеет внешний вид диалогового сообщения;
- настройки положения окна и его размера легко поменять в коде.
Я решил опубликовать свою грубую поделку на форум: вдруг кому пригодится. Делал для своего проекта, поэтому особо не заморачивался. Сейчас скрипт отображает максимум 2 строчки, а параметры меняются в функции, а не через константы в верхнем модуле. Если кому-то понадобится функционал получше (чтобы настройки удобнее задавать, отображать более 2 строчек и т.д.) - пишите сюда: чем смогу - помогу.
Спойлер код:
Сначала установите в проект движок CSCA:
Спойлер CSCA Core Script:
Код:=begin CSCA Core Script version: 1.0.7 Created by: Casper Gaming (http://www.caspergaming.com/) Scripts that REQUIRE this script to work: CSCA Colosseum CSCA Dungeon Tools CSCA Achievements CSCA Encyclopedia CSCA Treasure Maps CSCA Menu MOD CSCA SaveFile Plus CSCA Vehicle System CSCA Sidequests CSCA Professions Version History: 1.0.1 - Adds CSCA_Item class, used by scripts to get information about an item. 1.0.2 - Adds CSCA_Fish class, used by Vehicle System to get fishing data. 1.0.3 - Adds Window_HorzCommand fix to allow unlimited horizontal commands. 1.0.4 - Adds CSCA_Core class, used for csca script data that needs to be saved. 1.0.5 - Adds shorter access to variables/switches in Event script command. 1.0.6 - Adds troubleshooting error/warning reports. 1.0.7 - Adds vowel detection for strings. COMPATIBILITY PLACE THIS SCRIPT ABOVE ALL OTHER CSCA SCRIPTS! Compatible only for VXAce. IMPORTANT: ALL CSCA Scripts should be compatible with each other unless otherwise noted. FFEATURES This script includes classes and functions used by other CSCA Scripts. SETUP Plug n play. Make sure this script is ABOVE all other CSCA Scripts. CREDIT and TERMS: Please visit http://www.caspergaming.com/dev/terms_of_use/ for terms of use and credit guidelines =end $imported = {} if $imported.nil? $imported["CSCA-Core"] = true #============================================================================== # ** DataManager #------------------------------------------------------------------------------ # Handles csca class data. # Aliases: make_save_contents, create_game_objects, extract_save_contents #============================================================================== module DataManager #-------------------------------------------------------------------------- # alias method #-------------------------------------------------------------------------- class <<self; alias csca_core_create_game_objects create_game_objects; end def self.create_game_objects csca_core_create_game_objects $csca = CSCA_Core.new end #-------------------------------------------------------------------------- # overwrite method #-------------------------------------------------------------------------- class <<self; alias csca_core_save_contents make_save_contents; end def self.make_save_contents contents = csca_core_save_contents contents[:csca] = $csca contents end #-------------------------------------------------------------------------- # alias method #-------------------------------------------------------------------------- class <<self; alias csca_core_extract_save_contents extract_save_contents; end def self.extract_save_contents(contents) csca_core_extract_save_contents(contents) $csca = contents[:csca] end end #============================================================================== # ** CSCA_Window_Header #------------------------------------------------------------------------------ # This window displays the header window, used by many CSCA Scripts. #============================================================================== class CSCA_Window_Header < Window_Base #-------------------------------------------------------------------------- # Object Initialization #-------------------------------------------------------------------------- def initialize(x, y, width = Graphics.width, height = line_height*2, text) super(x, y, width, height) refresh(text) end #-------------------------------------------------------------------------- # Refresh #-------------------------------------------------------------------------- def refresh(text) contents.clear draw_text(0, 0, contents.width, line_height, text, 1) end end #============================================================================== # ** Game_Map #------------------------------------------------------------------------------ # Easy csca access to the map's note. #============================================================================== class Game_Map #-------------------------------------------------------------------------- # Get Map Note #-------------------------------------------------------------------------- def csca_map_note; @map.note; end end #============================================================================== # ** Window_HorzCommand #------------------------------------------------------------------------------ # Allow unlimited horizontal commands. # Overwrites: top_col= #============================================================================== class Window_HorzCommand < Window_Command #-------------------------------------------------------------------------- # Overwrite Method #-------------------------------------------------------------------------- def top_col=(col) col = 0 if col < 0 self.ox = col * (item_width + spacing) end end #============================================================================== # ** Game_Interpreter #------------------------------------------------------------------------------ # Shorter access to variables and switches. #============================================================================== class Game_Interpreter #-------------------------------------------------------------------------- # Get variables #-------------------------------------------------------------------------- def csca_v(var) $game_variables[var] end #-------------------------------------------------------------------------- # Get switches #-------------------------------------------------------------------------- def csca_s(swi) $game_switches[swi] end end #============================================================================== # ** CSCA_Item #------------------------------------------------------------------------------ # CSCA Items, used as rewards/wagers in various scripts. #============================================================================== class CSCA_Item attr_reader :id attr_reader :amount attr_reader :type #-------------------------------------------------------------------------- # Initialize #-------------------------------------------------------------------------- def initialize(amount,id,type) @id = id @amount = amount @type = type end end #============================================================================== # ** CSCA_Fish #------------------------------------------------------------------------------ # CSCA Fish, used to specify data about fish. #============================================================================== class CSCA_Fish attr_reader :item_id attr_reader :water_type attr_reader :weight attr_reader :region #-------------------------------------------------------------------------- # Initialize #-------------------------------------------------------------------------- def initialize(id, water, weight, region = 0) @item_id = id @water_type = water @weight = weight @region = region end end #============================================================================== # ** CSCA_Core #------------------------------------------------------------------------------ # Used to provide global methods for csca scripts. Data is included in save. #============================================================================== class CSCA_Core #-------------------------------------------------------------------------- # Initialize #-------------------------------------------------------------------------- def initialize end #-------------------------------------------------------------------------- # Report wrong setup #-------------------------------------------------------------------------- def report_error(error, script, suggestion, warning = false) string1 = warning ? "Warning: " : "Error: " msgbox(string1 + error + "\nOccurred in: " + script + "\nRecommended fix: " + suggestion) end #-------------------------------------------------------------------------- # Split number into millions, thousands, hundreds #-------------------------------------------------------------------------- def split_number(start) number = [] number[0] = start / 1000 / 1000 number[1] = start / 1000 % 1000 number[2] = start % 1000 return number end #-------------------------------------------------------------------------- # Split number into hours, minutes, seconds #-------------------------------------------------------------------------- def split_playtime(start) number = [] number[0] = start / 60 / 60 number[1] = start / 60 % 60 number[2] = start % 60 return number end #-------------------------------------------------------------------------- # Determine if letter is a vowel or not #-------------------------------------------------------------------------- def is_a_vowel(letter, space = false) letter.upcase return letter == "A" || letter == "E" || letter == "I" || letter == "O" || letter == "U" || (letter == "X" && space == true) end end
Ниже кода движка установите код менеджера тостов (на свой страх и риск можете поменять настройки окна в строчках 86-90):
Спойлер CSCA Toast Manager:
Код:=begin CSCA Toast Manager version: 1.1.2 (14.07.2020) Created by: Casper Gaming and Philes (Oleg Olegovich) Compatibility: Made for RPGVXAce IMPORTANT: ALL CSCA Scripts should be compatible with each other unless otherwise noted. Requires CSCA Core Script v1.0.4+ Suggested order: Paste below CSCA Core script, but above all other CSCA Scripts. FFEATURES Creates an easy-to-use toast system. Mainly a scripting tool, but you can create and call your own basic toasts as well. More information on how to do so in the script call section below. SETUP Set up required. Instructions below. Scripters: it is recommended to alias and add your custom display codes in the refresh method of CSCA_Window_Toast. If relying on this script to display toasts in your own script, please link to original CSCA Toast Manager script topic on rpgmakervxace.net ================================================================================ UPDATES: Version 1.0.0 -Original Script Version 1.1.0 -Toasts now global (not confined to the map scene). Certain scenes are excluded. Version 1.1.1 -Toasts now have a z value of 1000. ================================================================================ CREDIT and TERMS: Please visit http://www.caspergaming.com/dev/terms_of_use/ for terms of use and credit guidelines =end module CSCA module TOASTS #============================================================================== # ** Important Script Calls #============================================================================== # bt_reserve_toast(text1, text2) # Reserves a toast with 2 lines of centered text on it. # text1 is the first line, text2 is the second line. #============================================================================== # ** Begin Setup #============================================================================== SHOW_COUNT = 160 # Amount of frames to show each toast. Recommended 160. FADE_SPEED = 16 # Speed of fade in/out. Recommended 16. #============================================================================== # ** End Setup #============================================================================== end end $imported = {} if $imported.nil? $imported["CSCA-ToastManager"] = true #============================================================================== # ** Game_Interpreter #------------------------------------------------------------------------------ # Adds basic toast reservation method for non-scripters #============================================================================== class Game_Interpreter #-------------------------------------------------------------------------- # Basic Text toast reservation, creates a toast with 2 lines of text. #-------------------------------------------------------------------------- def bt_reserve_toast(text1, text2) $csca.reserve_toast([:csca_bt, text1, text2]) end end #============================================================================== # ** CSCA_Window_Toast #------------------------------------------------------------------------------ # This window handles toast data. #============================================================================== class CSCA_Window_Toast < Window_Base attr_reader :show_count attr_reader :toast_gone #-------------------------------------------------------------------------- # Object Initialization #-------------------------------------------------------------------------- def initialize(order) # Координаты левого верхнего угла тоста: x = 0 y = 0 # Ширина и высота тоста: width = Graphics.width / 3 height = line_height * 3 super(x, y, width, height) self.opacity = 0 self.contents_opacity = 0 self.z = 1000 @show_count = 0 @toast_gone = true end #-------------------------------------------------------------------------- # Get order height modifier #-------------------------------------------------------------------------- def get_order_modifier(order) return case order when :bottom; 6 when :middle; 3 when :top; 0 end end #-------------------------------------------------------------------------- # Frame Update #-------------------------------------------------------------------------- def update super if @show_count > 0 update_fadein @show_count -= 1 else update_fadeout unless @toast_gone end end #-------------------------------------------------------------------------- # Update Fadein #-------------------------------------------------------------------------- def update_fadein self.opacity += CSCA::TOASTS::FADE_SPEED self.contents_opacity += CSCA::TOASTS::FADE_SPEED end #-------------------------------------------------------------------------- # Update Fadeout #-------------------------------------------------------------------------- def update_fadeout self.opacity -= CSCA::TOASTS::FADE_SPEED self.contents_opacity -= CSCA::TOASTS::FADE_SPEED @toast_gone = true if self.opacity <= 0 && self.contents_opacity <= 0 end #-------------------------------------------------------------------------- # Writer method #-------------------------------------------------------------------------- def show_count=(amount) @show_count = amount @toast_gone = false end #-------------------------------------------------------------------------- # Refresh #-------------------------------------------------------------------------- def refresh(params) contents.clear if params[0] == :csca_bt #draw_text(0,0,contents.width,line_height,params[1],1) #draw_text(0,line_height,contents.width,line_height,params[2],1) params[1] = (params[1].is_a? Array) ? params[1] : [params[1]] params[2] = (params[2].is_a? Array) ? params[2] : [params[2]] params[1].each do |string| temp_string = string.gsub(/\\[^inpvg]\[\d{0,3}\]/) { "" } temp_string.gsub!(/\\i\[\d{0,3}\]/) { " " } temp_string.gsub!(/\\n\[(\d{0,3})\]/) { actor_name($1.to_i) } temp_string.gsub!(/\\p\[(\d{0,3})\]/) { party_member_name($1.to_i) } temp_string.gsub!(/\\v\[(\d+)\]/) { $game_variables[$1.to_i] } temp_string.gsub!(/\eG/i) { Vocab::currency_unit } #draw_text_ex(standard_padding, 0, params[1]) end params[1].each do |string| draw_text_ex(standard_padding, 0, string) end params[2].each do |string| temp_string = string.gsub(/\\[^inpvg]\[\d{0,3}\]/) { "" } temp_string.gsub!(/\\i\[\d{0,3}\]/) { " " } temp_string.gsub!(/\\n\[(\d{0,3})\]/) { actor_name($1.to_i) } temp_string.gsub!(/\\p\[(\d{0,3})\]/) { party_member_name($1.to_i) } temp_string.gsub!(/\\v\[(\d+)\]/) { $game_variables[$1.to_i] } temp_string.gsub!(/\eG/i) { Vocab::currency_unit } #draw_text_ex(standard_padding, line_height, params[2]) end params[2].each do |string| draw_text_ex(standard_padding, line_height, string) end end end end #============================================================================== # ** CSCA_Core #------------------------------------------------------------------------------ # Handles toast data. #Aliases: initialize #============================================================================== class CSCA_Core attr_reader :toasts #-------------------------------------------------------------------------- # Alias Method; object initialization #-------------------------------------------------------------------------- alias :csca_toast_init :initialize def initialize csca_toast_init @toasts = [] end #-------------------------------------------------------------------------- # Reserve Toast for display #-------------------------------------------------------------------------- def reserve_toast(params) return if SceneManager.no_toast_scene? @toasts.push(params) end end #============================================================================== # ** SceneManager #------------------------------------------------------------------------------ # Determines if the scene creates toasts. #============================================================================== module SceneManager #-------------------------------------------------------------------------- # Don't create toasts? #-------------------------------------------------------------------------- def self.no_toast_scene? scene_is?(Scene_Title) || scene_is?(Scene_Gameover) || scene_is?(Scene_Debug) || scene_is?(Scene_File) || scene_is?(Scene_Save) || scene_is?(Scene_Load) || scene_is?(Scene_End) || scene_is?(Scene_Name) end end #============================================================================== # ** Scene_Map #------------------------------------------------------------------------------ # Handles display of toasts #Aliases: create_all_windows, update #============================================================================== class Scene_Base #-------------------------------------------------------------------------- # Alias Method; Create All Windows #-------------------------------------------------------------------------- alias :csca_create_toast_windows :start def start csca_create_toast_windows create_toast_windows unless SceneManager.no_toast_scene? end #-------------------------------------------------------------------------- # Alias Method; Frame Update #-------------------------------------------------------------------------- alias :csca_toast_update :update def update csca_toast_update update_toasts end #-------------------------------------------------------------------------- # Create Toast Windows #-------------------------------------------------------------------------- def create_toast_windows @toast_bottom = CSCA_Window_Toast.new(:bottom) @toast_middle = CSCA_Window_Toast.new(:middle) @toast_top = CSCA_Window_Toast.new(:top) @toast_list = [@toast_bottom, @toast_middle, @toast_top] @toast_bottom.viewport = @viewport @toast_middle.viewport = @viewport @toast_top.viewport = @viewport end #-------------------------------------------------------------------------- # Update Toast Display #-------------------------------------------------------------------------- def update_toasts $csca.toasts.each do |params| break if params.nil? || no_toast_possible? create_toast(params) end end #-------------------------------------------------------------------------- # Check if all 3 toasts in use #-------------------------------------------------------------------------- def no_toast_possible? return !@toast_bottom.toast_gone && !@toast_middle.toast_gone && !@toast_top.toast_gone end #-------------------------------------------------------------------------- # Create Toast #-------------------------------------------------------------------------- def create_toast(params) $csca.toasts.delete(params) for toast in @toast_list.each if toast.toast_gone toast.refresh(params) toast.show_count = CSCA::TOASTS::SHOW_COUNT break end end end end
Чтобы использовать, в событии вызовите такой вот скрипт:
Код:bt_reserve_toast('<строка>', '<ещё одна строка>')
Спойлер скриншоты:
Социальные закладки